import React, {useEffect, useState} from 'react';
import {connect} from 'react-redux';
import {
  View,
  StyleSheet,
  ScrollView,
  Image,
  SafeAreaView,
  Alert,
  TouchableOpacity,
} from 'react-native';
import {Text, Tooltip} from '@rneui/themed';
import ArrowIcon from '@/assets/images/arrow_icon.png';
import {Icon} from '@rneui/themed';
import Overlay from '@/components/Overlay';
import {setUserInfo, setAuth, handleLogout} from '@/store/action/user';
import {handleSetLangList} from '@/store/action/lang';
import * as rootNavigation from '@/utils/rootNavigation';
import {getUserInfo, getAppLocaleList} from '@/apis/api';
import StorageUtils from '@/utils/storageUtils';
import {useTranslation} from 'react-i18next';
const Account = ({navigation, userInfo, handleLogout, handleSetLangList}) => {
  const {t} = useTranslation();
  const {msg} = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [open, setOpen] = React.useState(false);
  const [openId, setOpenId] = React.useState(false);
  const [langList, setLangList] = React.useState([]);
  const [currentUser, setCurrentUser] = React.useState(userInfo);
  const onLogout = () => {
    Alert.alert(t('sys_tip'), t('sys_logoutConfirmTip'), [
      {
        text: t('sys_cancel'),
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel',
      },
      {
        text: t('sys_confirm'),
        onPress: () => {
          rootNavigation.reset('Login');
          handleLogout();
        },
      },
    ]);
  };
  const handleSetting = () => {
    rootNavigation.push('Setting');
  };
  const handleLanguage = () => {
    rootNavigation.push('Language');
  };

  // 跳转流程中心
  const handleToProcessCenter = () => {
    rootNavigation.push('ProessCenter');
  };
  const getAppLangList = async () => {
    const res = await getAppLocaleList();
    const languageGroups = res?.data || [];
    setLangList(languageGroups);
    handleSetLangList(languageGroups);
  };
  useEffect(() => {
    setIsLoading(false);
    getUserInfo()
      .then(res => {
        if (res?.data?.sysUser) {
          setCurrentUser(res.data.sysUser);
        }
      })
      .finally(() => {
        setIsLoading(false);
      });
    getAppLangList();
  }, [msg]);

  return (
    <SafeAreaView style={styles.contentView} forceInset={{top: 'always'}}>
      <Overlay isShow={isLoading} />
      <ScrollView>
        <View style={styles.titleView}>
          <View style={styles.profileView}>
            <Image
              source={require('@/assets/images/pic.png')}
              style={styles.imageStyle}
            />
            <View style={{marginLeft: 10, flex: 1}}>
              <Tooltip
                visible={false}
                onOpen={() => setOpen(true)}
                onClose={() => setOpen(false)}
                popover={
                  <Text style={{color: '#fff'}}>
                    {t('sys_usernameWithColon')}
                    {currentUser.nickname ||
                      currentUser.name ||
                      currentUser.username}
                  </Text>
                }>
                <Text numberOfLines={1} h5 style={{color: '#fff'}}>
                  {t('sys_usernameWithColon')}
                  {currentUser.nickname ||
                    currentUser.name ||
                    currentUser.username}
                </Text>
              </Tooltip>
              <Tooltip
                visible={false}
                onOpen={() => setOpenId(true)}
                onClose={() => setOpenId(false)}
                popover={
                  <Text style={{color: '#fff'}}>
                    {' '}
                    {t('sys_id')}
                    {userInfo.user_id}
                  </Text>
                }>
                <Text
                  numberOfLines={1}
                  h5
                  style={{color: '#fff', marginTop: 8}}>
                  {t('sys_id')}
                  {userInfo.user_id}
                </Text>
              </Tooltip>
            </View>
          </View>
        </View>
        <View style={styles.listView}>
          <TouchableOpacity onPress={() => navigation.navigate('PwdChange')}>
            <View style={styles.options}>
              <View style={styles.optionsLeft}>
                <Icon
                  name="lock-outline"
                  color="#fff"
                  iconStyle={[
                    styles.optionIcon,
                    {backgroundColor: 'rgb(0,137,253)'},
                  ]}
                />
                <Text style={styles.optionsText}>{t('sys_editPassword')}</Text>
              </View>
              <Image source={ArrowIcon} style={styles.icon} />
            </View>
          </TouchableOpacity>
          <TouchableOpacity onPress={handleSetting}>
            <View style={styles.options}>
              <View style={styles.optionsLeft}>
                <Icon
                  name="settings"
                  color="#fff"
                  iconStyle={[
                    styles.optionIcon,
                    {backgroundColor: 'rgb(33,172,99)'},
                  ]}
                />
                <Text style={styles.optionsText}>{t('sys_setting')}</Text>
              </View>
              <Image source={ArrowIcon} style={styles.icon} />
            </View>
          </TouchableOpacity>
          {/* process */}
          <TouchableOpacity onPress={handleToProcessCenter}>
            <View style={styles.options}>
              <View style={styles.optionsLeft}>
                <Icon
                  name="approval"
                  color="#fff"
                  iconStyle={[
                    styles.optionIcon,
                    {backgroundColor: '#FF9E16'},
                  ]}
                />
                <Text style={styles.optionsText}>
                  {t('sys_processCenter')}
                </Text>
              </View>
              <Image source={ArrowIcon} style={styles.icon} />
            </View>
          </TouchableOpacity>
          {/* Logout */}
          {langList.length > 1 ? (
            <TouchableOpacity onPress={handleLanguage}>
              <View style={styles.options}>
                <View style={styles.optionsLeft}>
                  <Icon
                    name="translate"
                    color="#fff"
                    iconStyle={[
                      styles.optionIcon,
                      {backgroundColor: '#1677ff'},
                    ]}
                  />
                  <Text style={styles.optionsText}>
                    {t('sys_languageSetting')}
                  </Text>
                </View>
                <Image source={ArrowIcon} style={styles.icon} />
              </View>
            </TouchableOpacity>
          ) : null}
          <TouchableOpacity onPress={onLogout}>
            <View style={styles.options}>
              <View style={styles.optionsLeft}>
                <Icon
                  name="logout"
                  color="#fff"
                  iconStyle={[
                    styles.optionIcon,
                    {backgroundColor: 'rgb(255,105,103)'},
                  ]}
                />
                <Text style={styles.optionsText}>{t('sys_logout')}</Text>
              </View>
              <Image source={ArrowIcon} style={styles.icon} />
            </View>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  contentView: {
    backgroundColor: '#fff',
    flex: 1,
    justifyContent: 'flex-start',
  },
  titleView: {
    height: 120,
    marginHorizontal: 15,
    marginTop: 20,
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  listView: {
    backgroundColor: '#fff',
  },
  icon: {
    width: 26,
    height: 26,
  },
  imageStyle: {
    width: 70,
    height: 70,
    //    borderRadius: 40,
    marginLeft: 15,
  },
  profileView: {
    marginBottom: 20,
    flex: 1,
    borderRadius: 10,
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#00a7ff',
  },
  options: {
    display: 'flex',
    height: 60,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    paddingLeft: 20,
    paddingRight: 20,
    // borderTopColor: "#DFDFDF",
    // borderTopWidth: 0.5,
    borderBottomColor: '#DFDFDF',
    borderBottomWidth: 0.5,
  },
  optionsLeft: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  optionIcon: {
    padding: 5,
    borderRadius: 10,
    marginRight: 10,
  },
  optionsText: {
    fontSize: 18,
    marginTop: 5,
  },
  titleStyle: {
    fontSize: 18,
    fontWeight: '600',
    color: 'white',
    marginTop: 3,
  },
});

export default connect(
  state => ({
    userInfo: state.user.userInfo,
    auth: state.user.auth,
  }),
  dispatch => ({
    handleLogout: () => dispatch(handleLogout()),
    setUserInfo: data => dispatch(setUserInfo(data)),
    setAuth: token => dispatch(setAuth(token)),
    handleSetLangList: lang => dispatch(handleSetLangList(lang)),
  }),
)(Account);
